package hg.demo.mybatis.plus.chatgpt;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;

public class StudentInfoManagementSystem extends JFrame {

    private static final String DATA_FILE = "D:\\tmp\\students.txt";

    private JLabel labelId;
    private JLabel labelName;
    private JLabel labelGender;
    private JLabel labelAge;
    private JLabel labelMajor;

    private JTextField textId;
    private JTextField textName;
    private JRadioButton radioMale;
    private JRadioButton radioFemale;
    private JTextField textAge;
    private JComboBox<String> comboMajor;

    private JButton buttonAdd;
    private JButton buttonUpdate;
    private JButton buttonDelete;
    private JButton buttonClear;

    private JTable table;
    private JScrollPane scrollPane;

    private StudentTableModel tableModel;

    public StudentInfoManagementSystem() {
        // 初始化界面组件
        labelId = new JLabel("学号：");
        labelName = new JLabel("姓名：");
        labelGender = new JLabel("性别：");
        labelAge = new JLabel("年龄：");
        labelMajor = new JLabel("专业：");

        textId = new JTextField();
        textName = new JTextField();
        radioMale = new JRadioButton("男");
        radioFemale = new JRadioButton("女");
        textAge = new JTextField();
        comboMajor = new JComboBox<>(new String[]{"计算机科学与技术", "电子信息工程", "通信工程", "数学与应用数学", "物理学", "化学", "生物学", "地理科学", "心理学", "政治学与公安学", "历史学", "新闻学", "英语", "法语", "日语", "德语", "韩语", "俄语", "其他"});

        buttonAdd = new JButton("添加");
        buttonUpdate = new JButton("修改");
        buttonDelete = new JButton("删除");
        buttonClear = new JButton("清空");

        // 设置性别单选按钮组
        ButtonGroup genderGroup = new ButtonGroup();
        genderGroup.add(radioMale);
        genderGroup.add(radioFemale);

        // 初始化表格模型
        tableModel = new StudentTableModel();

        // 初始化表格
        table = new JTable(tableModel);
        scrollPane = new JScrollPane(table);

        // 设置表格列宽
        table.getColumnModel().getColumn(0).setPreferredWidth(100);
        table.getColumnModel().getColumn(1).setPreferredWidth(100);
        table.getColumnModel().getColumn(2).setPreferredWidth(100);
        table.getColumnModel().getColumn(3).setPreferredWidth(100);
        table.getColumnModel().getColumn(4).setPreferredWidth(200);

        // 设置表格行高
        table.setRowHeight(30);

        // 设置界面布局
        setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();

        c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(5, 5, 5, 5);

        c.gridx = 0;
        c.gridy = 0;
        add(labelId, c);

        c.gridx = 1;
        c.gridy = 0;
        add(textId, c);

        c.gridx = 2;
        c.gridy = 0;
        add(labelName, c);

        c.gridx = 3;
        c.gridy = 0;
        add(textName, c);

        c.gridx = 0;
        c.gridy = 1;
        add(labelGender, c);

        c.gridx = 1;
        c.gridy = 1;
        add(radioMale, c);

        c.gridx = 2;
        c.gridy = 1;
        add(radioFemale, c);

        c.gridx = 3;
        c.gridy = 1;
        add(labelAge, c);

        c.gridx = 4;
        c.gridy = 1;
        add(textAge, c);

        c.gridx = 0;
        c.gridy = 2;
        add(labelMajor, c);

        c.gridx = 1;
        c.gridy = 2;
        add(comboMajor, c);

        c.gridx = 2;
        c.gridy = 2;
        add(buttonAdd, c);

        c.gridx = 3;
        c.gridy = 2;
        add(buttonUpdate, c);

        c.gridx = 4;
        c.gridy = 2;
        add(buttonDelete, c);

        c.gridx = 5;
        c.gridy = 2;
        add(buttonClear, c);

        c.gridx = 0;
        c.gridy = 3;
        c.gridwidth = 6;
        c.fill = GridBagConstraints.BOTH;
        c.weightx = 1.0;
        c.weighty = 1.0;
        add(scrollPane, c);

        // 加载数据
        loadData();

        // 设置界面属性
        setTitle("学生信息管理系统");
        setSize(800, 600);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // 添加按钮监听器
        buttonAdd.addActionListener(new AddActionListener());
        buttonUpdate.addActionListener(new UpdateActionListener());
        buttonDelete.addActionListener(new DeleteActionListener());
        buttonClear.addActionListener(new ClearActionListener());
    }

    private void loadData() {
        List<Student> students = new ArrayList<>();

        // 从文件中加载数据
        try (BufferedReader reader = new BufferedReader(new FileReader(DATA_FILE))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] tokens = line.split(",");
                int id = Integer.parseInt(tokens[0]);
                String name = tokens[1];
                String gender = tokens[2];
                int age = Integer.parseInt(tokens[3]);
                String major = tokens[4];

                students.add(new Student(id, name, gender, age, major));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 将数据设置到表格模型中
        tableModel.setStudents(students);
    }

    private void saveData() {
        List<Student> students = tableModel.getStudents();

        // 将数据保存到文件中
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(DATA_FILE))) {
            for (Student student : students) {
                String line = String.format("%d,%s,%s,%d,%s", student.getId(), student.getName(), student.getGender(), student.getAge(), student.getMajor());
                writer.write(line);
                writer.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void clearForm() {
        textId.setText("");
        textName.setText("");
        radioMale.setSelected(true);
        textAge.setText("");
        comboMajor.setSelectedIndex(0);
    }

    private class AddActionListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String id = textId.getText().trim();
            String name = textName.getText().trim();
            String gender = radioMale.isSelected() ? "男" : "女";
            String age = textAge.getText().trim();
            String major = comboMajor.getSelectedItem().toString();

            if (id.length() == 0 || name.length() == 0 || age.length() == 0) {
                JOptionPane.showMessageDialog(StudentInfoManagementSystem.this, "请填写完整信息", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            try {
                int idValue = Integer.parseInt(id);
                int ageValue = Integer.parseInt(age);

                Student student = new Student(idValue, name, gender, ageValue, major);
                tableModel.addStudent(student);
                saveData();

                clearForm();
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(StudentInfoManagementSystem.this, "请填写正确的数字格式", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private class UpdateActionListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String id = textId.getText().trim();
            String name = textName.getText().trim();
            String gender = radioMale.isSelected() ? "男" : "女";
            String age = textAge.getText().trim();
            String major = comboMajor.getSelectedItem().toString();

            if (id.length() == 0 || name.length() == 0 || age.length() == 0) {
                JOptionPane.showMessageDialog(StudentInfoManagementSystem.this, "请填写完整信息", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            try {
                int idValue = Integer.parseInt(id);
                int ageValue = Integer.parseInt(age);

                Student student = new Student(idValue, name, gender, ageValue, major);
                tableModel.updateStudent(student);
                saveData();

                clearForm();
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(StudentInfoManagementSystem.this, "请填写正确的数字格式", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }


    private class DeleteActionListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            int[] rows = table.getSelectedRows();
            if (rows.length == 0) {
                JOptionPane.showMessageDialog(StudentInfoManagementSystem.this, "请选择要删除的学生", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            int result = JOptionPane.showConfirmDialog(StudentInfoManagementSystem.this, "确定删除所选学生吗？", "确认", JOptionPane.YES_NO_OPTION);
            if (result != JOptionPane.YES_OPTION) {
                return;
            }

            for (int i = rows.length - 1; i >= 0; i--) {
                tableModel.deleteStudent(rows[i]);
            }
            saveData();
        }
    }

    private class ClearActionListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            clearForm();
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new StudentInfoManagementSystem().setVisible(true);
            }
        });
    }
}